package com.woniu.darryringmall.admin.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.woniu.darryringmall.admin.Request.GoodsVO;
import com.woniu.darryringmall.front.entity.Goods;
import com.woniu.darryringmall.front.entity.Images;
import com.woniu.darryringmall.front.entity.Order;
import com.woniu.darryringmall.front.service.GoodsService;
import com.woniu.darryringmall.front.service.ImagesService;
import com.woniu.darryringmall.utils.ResponseData;
import com.woniu.darryringmall.utils.ResponseUtils;
import com.woniu.darryringmall.utils.ResultStateCode;
import com.woniu.darryringmall.utils.TencentCOSUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

@RestController("adminGoods")
@RequestMapping("admin/goods")
public class GoodsController {
    @Autowired
    private GoodsService goodsService;
    @Autowired
    private ImagesService imagesService;

    @RequestMapping("list")
    public ResponseData getAll(Integer current, Goods goods) {
        if (current == null) {
            current = 1;
        }
        Page<Goods> page = new Page<>(current, 8);
        QueryWrapper<Goods> queryWrapper = new QueryWrapper<>();
        if (goods.getName() != null && goods.getName().trim().length() != 0) {
            queryWrapper.like("name", goods.getName());
        }
        if (goods.getCategoryId() != 0) {
            queryWrapper.eq("categoryid", goods.getCategoryId());
        }
        if (goods.getPushTime() != null && goods.getPushTime().trim().length() != 0) {
            queryWrapper.ge("pushTime", goods.getPushTime());
        }
        page = goodsService.page(page, queryWrapper);
        return ResponseUtils.getResponseData(ResultStateCode.SUCCESS, "操作成功", page);
    }

    @RequestMapping("images")
    public ResponseData saveImages(MultipartFile[] files) throws IOException {
        //保存图片的路径
        List<String> images = new ArrayList<>();
        for (MultipartFile file : files) {
//            String oldName = file.getOriginalFilename();
//            String suffix = oldName.substring(oldName.lastIndexOf("."));
//            String newName = UUID.randomUUID().toString().replaceAll("-", "") + suffix;
//            String staticPath ="/" + ClassUtils.getDefaultClassLoader().getResource("static").getPath() + "/imagestest/";
//            file.transferTo(new File(staticPath + newName));
            images.add(TencentCOSUtil.uploadfile(file));
        }
        return ResponseUtils.getResponseData(ResultStateCode.SUCCESS, "操作成功", images);
    }

    @RequestMapping("add")
    public ResponseData add(@RequestBody GoodsVO goodsVO) {
        Goods goods = goodsVO.getGoods();
        if (goods.getName() == null || goods.getName().trim().length() < 2 || goods.getName().trim().length() > 20) {
            return ResponseUtils.getResponseData(ResultStateCode.FAIL, "操作失败", "商品名字必须在2-20位之间");
        }
        QueryWrapper<Goods> queryWrapper = new QueryWrapper();
        queryWrapper.eq("name", goods.getName());
        if (goodsService.getOne(queryWrapper) != null) {
            return ResponseUtils.getResponseData(ResultStateCode.FAIL, "操作失败", "商品名称重复");
        }
        if (goods.getCategoryId() == 0) {
            return ResponseUtils.getResponseData(ResultStateCode.FAIL, "操作失败", "必须选择一个类别");
        }
        if (goods.getDescription() == null || goods.getDescription().trim().length() == 0) {
            return ResponseUtils.getResponseData(ResultStateCode.FAIL, "操作失败", "描述不能为空");
        }

        goodsService.add(goodsVO);
        return ResponseUtils.SUCCESS;
    }

    /**
     * 按条件更新数据，还没有写图片更新，有了页面再加参数MultipartFile[] files
     * @param goodsVO
     * @return
     */
    @RequestMapping("update")
    public ResponseData update(@RequestBody GoodsVO goodsVO) {
        System.out.println(goodsVO);
        Goods goods = goodsVO.getGoods();
        Goods oldGoods = goodsService.getById(goods.getId());
        if (oldGoods != null) {
            if (!oldGoods.getName().equals(goods.getName())) {
                if (goods.getName() == null || goods.getName().trim().length() < 2 || goods.getName().trim().length() > 20) {
                    return ResponseUtils.getResponseData(ResultStateCode.FAIL, "操作失败", "商品名字必须在2-20位之间");
                }
                QueryWrapper<Goods> queryWrapper = new QueryWrapper();
                queryWrapper.eq("name", goods.getName());
                if (goodsService.getOne(queryWrapper) != null) {
                    return ResponseUtils.getResponseData(ResultStateCode.FAIL, "操作失败", "商品名称重复");
                }
            }
        }

        goodsService.conditionUpdate(goodsVO);
        return ResponseUtils.SUCCESS;
    }

    @RequestMapping("del/{id}")
    public ResponseData del(@PathVariable int id) {
        goodsService.del(id);
        return ResponseUtils.SUCCESS;
    }

    @RequestMapping("getById/{id}")
    public ResponseData getById(@PathVariable int id) {
        QueryWrapper<Images> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("goodsid", id);
        List<Images> images = imagesService.list(queryWrapper);
        List<String> urls = new ArrayList<>();
        images.forEach(e -> urls.add(e.getLink()));
        GoodsVO goodsVO = new GoodsVO();
        goodsVO.setUrlList(urls);
        goodsVO.setGoods(goodsService.getById(id));
        return ResponseUtils.getResponseData(ResultStateCode.SUCCESS, "操作成功", goodsVO);
    }

    /**
     * 更新商品状态，上架或者下架
     * @param id
     * @return
     */
    @RequestMapping("upOrDown/{id}/{str}")
    public ResponseData upOrDown(@PathVariable int id, @PathVariable String str) {
        UpdateWrapper<Goods> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("id", id);
        if (str.equals("up")) {
            updateWrapper.set("status", "y");
        } else {
            updateWrapper.set("status", "n");
        }
        goodsService.update(updateWrapper);
        return ResponseUtils.SUCCESS;
    }
}
